package com.hllxd.hism.star.basic.service.service;


import com.hllxd.hism.star.basic.service.dao.mapper.doris.DorisMapper;
import com.hllxd.hism.star.basic.service.model.BasicExcelEntity;
import com.hllxd.hism.star.basic.service.model.doris.WordChartEntity;
import com.hllxd.hism.star.basic.service.model.doris.WordTopEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 跳房子订单实现类
 *
 * @author lixiyong
 * @date 2020/12/20 16:15
 */
@Slf4j
@Service("wordTopService")
public class WordTopServiceImpl implements WordTopService {

    @Autowired
    private DorisMapper dorisMapper;

    public static void main(String[] args) {

        LocalDate parse = LocalDate.parse("2022-04-06");

        System.out.println(parse.getYear() + "," + parse.getMonthValue() + "");
//        LocalDateTime myTime = LocalDateTime.of(LocalDateTime.now().getYear(), LocalDateTime.now().getMonth(), LocalDateTime.now().getDayOfMonth(), 0, 0);
//        DayOfWeek dayOfWeek = ;

//        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0).minusDays(1);
//
//        System.out.println(time);

//        LocalDate startDate = LocalDate.parse("2022-03-05");
////        LocalDateTime startTime = LocalDateTime.parse("2022-02-05", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        LocalDateTime newDataTime = LocalDateTime.now().minusDays(1);
//        long until = startDate.until(newDataTime, ChronoUnit.DAYS);
//        ArrayList<String> list = new ArrayList<>();
//        for (int i = 0; i <= until; i++) {
//            list.add(startDate.plusDays(i).toString());
//        }
//        System.out.println(list);
//        UUID uuid = UUID.randomUUID();
//        System.out.println(uuid.toString());
//
//        LocalDateTime time = LocalDateTime.now().minusDays(1);
//        int dayOfMonth = time.getDayOfMonth() - 1;
//        LocalDateTime start = time.minusDays(dayOfMonth);
//        LocalDateTime lastStartMon = start.minusMonths(1);
//        LocalDateTime lastEndMon = time.minusMonths(1);
//        String startTime = lastStartMon.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        String endTime = lastEndMon.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//
////        LocalDateTime time = LocalDateTime.now();
////        int dayOfWeek = time.getDayOfWeek().getValue();
////        System.out.println(dayOfWeek);
////        if (dayOfWeek == 7) {
////            dayOfWeek = 0;
////        }
////        LocalDateTime sWeekTime = time.minusDays(dayOfWeek).minusDays(14);
////        LocalDateTime eWeekTime = time.minusDays(dayOfWeek).minusDays(8);
////        String startTime = sWeekTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
////        String endTime = eWeekTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        System.out.println(startTime + "," + endTime);
////        int dayOfMonth = time.getDayOfMonth() - 1;
//
//        LocalDateTime start = time.minusDays(dayOfMonth);
////        LocalDateTime end = time.;
//        System.out.println(start);
//        System.out.println(time);
//        for (long i = 0; i < dayOfYear; i++) {
//            LocalDateTime calTime = myTime.minusDays(i);
//            System.out.println(calTime.getYear() + "-" + calTime.getMonthValue() + "-" + calTime.getDayOfMonth());
//        }


    }

    @Override
    public Map<String, Object> list(Map<String, String> paramMap) {
        HashMap<String, Object> conditionMap = new HashMap<>();
        String interval = paramMap.get("interval");
        String[] dateInterval = handleInterval(interval);
        log.info("查询周期：开始:{},结束:{}", dateInterval[0], dateInterval[1]);
        conditionMap.put("startDt", dateInterval[0]);
        conditionMap.put("endDt", dateInterval[1]);
        conditionMap.put("zpsrc", "58");
        conditionMap.put("platform", paramMap.get("endpoint"));
        conditionMap.put("areaName", paramMap.get("areaName"));
        String searchType = paramMap.get("searchType");
        if (searchType != null && !"".equals(searchType)) {
            if (searchType.equals("inputWord")) {
                conditionMap.put("searchType", "'输入词'");
            } else if (searchType.equals("systemWord")) {
                conditionMap.put("searchType", "'发现词', '历史词', '联想词', '搜索提示词'");
            } else {
                conditionMap.put("searchType", "");
            }
        }

        List<WordTopEntity> wubaList = dorisMapper.listInwordInfo(conditionMap);
        conditionMap.put("zpsrc", "ganji");
        List<WordTopEntity> ganjiList = dorisMapper.listInwordInfo(conditionMap);


        List<String> areaNames = dorisMapper.listAreaName(conditionMap);

        Map<String, Object> map = new HashMap<>();
        map.put("wuba", wubaList);
        map.put("ganji", ganjiList);
        map.put("areaNames", areaNames);
        return map;
    }

    @Override
    public Map<String, Object> listByParam(Map<String, String> paramMap) {
        HashMap<String, Object> conditionMap = new HashMap<>();
        String interval = paramMap.get("interval");
        String[] dateInterval = handleInterval(interval);
        String[] lastDateInterval = handleLastInterval(interval);
        log.info("查询周期：开始:{},结束:{},上周期开始：{},上周起结束：{}", dateInterval[0], dateInterval[1], lastDateInterval[0], lastDateInterval[1]);
        conditionMap.put("startDt", dateInterval[0]);
        conditionMap.put("endDt", dateInterval[1]);
        conditionMap.put("lastStartDt", lastDateInterval[0]);
        conditionMap.put("lastEndDt", lastDateInterval[1]);
        conditionMap.put("zpsrc", paramMap.get("zpsrc"));
        conditionMap.put("platform", paramMap.get("endpoint"));
        conditionMap.put("areaName", paramMap.get("areaName"));
        conditionMap.put("catename", paramMap.get("catename"));
        conditionMap.put("inword", paramMap.get("inword"));
        String searchType = paramMap.get("searchType");
        if (searchType != null && !"".equals(searchType)) {
            if (searchType.equals("inputWord")) {
                conditionMap.put("searchType", "'输入词'");
            } else if (searchType.equals("systemWord")) {
                conditionMap.put("searchType", "'发现词', '历史词', '联想词', '搜索提示词'");
            } else {
                conditionMap.put("searchType", "");
            }
        }

        String aggType = paramMap.get("aggType");
        List<WordTopEntity> dataList;
        if (!"".equals(aggType)) {
            conditionMap.put("aggType", aggType);
            dataList = dorisMapper.listInwordInfoAgg(conditionMap);
        } else {
            dataList = dorisMapper.listInwordInfoWithRadio(conditionMap);
        }

        List<String> areaNames = dorisMapper.listAreaName(conditionMap);

        Map<String, Object> map = new HashMap<>();
        map.put("dataList", dataList);
        map.put("areaNames", areaNames);
        return map;
    }

    @Override
    public Map<String, Object> listAreaCateAgg(Map<String, String> paramMap) {
        HashMap<String, Object> conditionMap = new HashMap<>();
        String interval = paramMap.get("interval");
        String[] dateInterval = handleInterval(interval);
        String[] lastDateInterval = handleLastInterval(interval);
        log.info("查询周期：开始:{},结束:{},上周期开始：{},上周起结束：{}", dateInterval[0], dateInterval[1], lastDateInterval[0], lastDateInterval[1]);
        conditionMap.put("startDt", dateInterval[0]);
        conditionMap.put("endDt", dateInterval[1]);
        conditionMap.put("zpsrc", paramMap.get("zpsrc"));
        conditionMap.put("platform", paramMap.get("endpoint"));
        conditionMap.put("areaName", paramMap.get("areaName"));
        conditionMap.put("catename", paramMap.get("catename"));
        String searchType = paramMap.get("searchType");
        if (searchType != null && !"".equals(searchType)) {
            if (searchType.equals("inputWord")) {
                conditionMap.put("searchType", "'输入词'");
            } else if (searchType.equals("systemWord")) {
                conditionMap.put("searchType", "'发现词', '历史词', '联想词', '搜索提示词'");
            } else {
                conditionMap.put("searchType", "");
            }
        }

        List<WordTopEntity> dataList = dorisMapper.listAreaCateAgg(conditionMap);
        List<String> areaNames = dorisMapper.listAreaName(conditionMap);

        Map<String, Object> map = new HashMap<>();
        map.put("dataList", dataList);
        map.put("areaNames", areaNames);
        return map;
    }

    private String[] handleInterval(String interval) {
        LocalDateTime localDateTime = LocalDateTime.now().minusDays(1);
        switch (interval) {
            case "week":
                return getWeekInterval();
            case "month":
                return getMonthInterval();
            case "day":
            default:
                String startTime = dorisMapper.getMaxDt();
//                String startTime = localDateTime.getYear() + "-" + localDateTime.getMonthValue() + "-" + localDateTime.getDayOfMonth();
                return new String[]{startTime, startTime};
        }
    }

    private String[] handleLastInterval(String interval) {
        LocalDateTime localDateTime = LocalDateTime.now().minusDays(1);
        switch (interval) {
            case "week":
                return getLastWeekInterval();
            case "month":
                return getLastMonthInterval();
            case "day":
            default:
                String maxDt = dorisMapper.getMaxDt();
                LocalDate maxDtLD = LocalDate.parse(maxDt);
                LocalDate lastLocalDate = maxDtLD.minusDays(1);
//                LocalDateTime lastLocalDateTime = localDateTime.minusDays(1);
                String startTime = lastLocalDate.getYear() + "-" + lastLocalDate.getMonthValue() + "-" + lastLocalDate.getDayOfMonth();
                return new String[]{startTime, startTime};
        }
    }

    private String[] getLastMonthInterval() {
        LocalDateTime time = LocalDateTime.now().minusDays(1);
        int dayOfMonth = time.getDayOfMonth() - 1;
        LocalDateTime start = time.minusDays(dayOfMonth);
        LocalDateTime lastStartMon = start.minusMonths(1);
        LocalDateTime lastEndMon = time.minusMonths(1);
        String startTime = lastStartMon.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String endTime = lastEndMon.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return new String[]{startTime, endTime};
    }

    private String[] getLastWeekInterval() {
        LocalDateTime time = LocalDateTime.now();
        int dayOfWeek = time.getDayOfWeek().getValue();
        System.out.println(dayOfWeek);
        if (dayOfWeek == 7) {
            dayOfWeek = 0;
        }
        LocalDateTime sWeekTime = time.minusDays(dayOfWeek).minusDays(14);
        LocalDateTime eWeekTime = time.minusDays(dayOfWeek).minusDays(8);
        String startTime = sWeekTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String endTime = eWeekTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return new String[]{startTime, endTime};
    }

    private String[] getMonthInterval() {
        LocalDateTime time = LocalDateTime.now().minusDays(1);
        int dayOfMonth = time.getDayOfMonth() - 1;
        LocalDateTime start = time.minusDays(dayOfMonth);
        String startTime = start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String endTime = time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return new String[]{startTime, endTime};
    }

    private String[] getWeekInterval() {
        LocalDateTime time = LocalDateTime.now();
        int dayOfWeek = time.getDayOfWeek().getValue();
        System.out.println(dayOfWeek);
        if (dayOfWeek == 7) {
            dayOfWeek = 0;
        }
        LocalDateTime sWeekTime = time.minusDays(dayOfWeek).minusDays(7);
        LocalDateTime eWeekTime = time.minusDays(dayOfWeek).minusDays(1);
        String startTime = sWeekTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String endTime = eWeekTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return new String[]{startTime, endTime};
    }

    private String[] getYearInterval() {
        LocalDateTime time = LocalDateTime.now();
        LocalDateTime time2 = time.minusDays(366);
        String startTime = time2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String endTime = time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return new String[]{startTime, endTime};
    }

    @Override
    public WordChartEntity getWordChart(Map<String, String> paramMap) {
        String[] yearInterval = getYearInterval();

        HashMap<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("startDt", yearInterval[0]);
        conditionMap.put("endDt", yearInterval[1]);
        conditionMap.put("zpsrc", paramMap.get("business").equals("wuba") ? "58" : "ganji");
        conditionMap.put("platform", paramMap.get("endpoint"));
        conditionMap.put("areaName", paramMap.get("areaName"));
        conditionMap.put("inword", paramMap.get("inword"));
        conditionMap.put("catename", paramMap.get("catename"));
        String searchType = paramMap.get("searchType");
        if (searchType != null && !"".equals(searchType)) {
            if (searchType.equals("inputWord")) {
                conditionMap.put("searchType", "'输入词'");
            } else if (searchType.equals("systemWord")) {
                conditionMap.put("searchType", "'发现词', '历史词', '联想词', '搜索提示词'");
            } else {
                conditionMap.put("searchType", "");
            }
        }

        List<WordTopEntity> wordTopEntities = dorisMapper.listWordChart(conditionMap);
        List<String> areaNames = dorisMapper.listAreaName(conditionMap);
        ArrayList<String> xList = new ArrayList<>();
        ArrayList<Integer> values = new ArrayList<>();
        int valueIndex = 0;
        if (wordTopEntities.size() >= 1) {
            String startDateStr = wordTopEntities.get(0).getDt();
            LocalDate startDate = LocalDate.parse(startDateStr);
            LocalDateTime newDataTime = LocalDateTime.now().minusDays(1);
            long until = startDate.until(newDataTime, ChronoUnit.DAYS);
            for (int i = 0; i <= until; i++) {
                String dateStr = startDate.plusDays(i).toString();
                xList.add(dateStr);
                if (wordTopEntities.size() > valueIndex) {
                    WordTopEntity entity = wordTopEntities.get(valueIndex);
                    if (dateStr.equals(entity.getDt())) {
                        values.add(Integer.parseInt(entity.getSearchPv()));
                        valueIndex++;
                    } else {
                        values.add(null);
                    }
                } else {
                    values.add(null);
                }

            }
        }
        WordChartEntity entity = new WordChartEntity();
        entity.setXAxisData(xList);
        entity.setValues(values);
        entity.setAreaNames(areaNames);

        return entity;
    }

    @Override
    public Map<String, List<WordTopEntity>> getAreaWordsTop(HashMap<String, String> paramMap) {
        HashMap<String, Object> conditionMap = new HashMap<>();

        String[] dateInterval = handleInterval("day");
        log.info("getAreaWordsTop查询周期：开始:{},结束:{}", dateInterval[0], dateInterval[1]);
        conditionMap.put("startDt", dateInterval[0]);
        conditionMap.put("endDt", dateInterval[1]);
        conditionMap.put("zpsrc", paramMap.get("business").equals("wuba") ? "58" : "ganji");
        conditionMap.put("areaNames", "'北京','广州','深圳','上海','成都','重庆','杭州','武汉','长沙','东莞'");
        List<WordTopEntity> areaWordsTop = dorisMapper.getAreaWordsTop(conditionMap);
        HashMap<String, List<WordTopEntity>> result = new HashMap<>();
        String firstName = null;
        List<WordTopEntity> tempList = null;
        for (int i = 0; i < areaWordsTop.size(); i++) {
            String areaname = areaWordsTop.get(i).getAreaname();
            if (i == 0) {
                firstName = areaname;
                tempList = new ArrayList<>();
            }
            if (!areaname.equals(firstName)) {
                result.put(firstName, tempList);
                firstName = areaname;
                tempList = new ArrayList<>();
            }
            tempList.add(areaWordsTop.get(i));
        }
        result.put(firstName, tempList);


        return result;
    }

    @Override
    public Map<String, List<WordTopEntity>> getCateWordsTop(HashMap<String, String> paramMap) {

        HashMap<String, Object> conditionMap = new HashMap<>();

        String[] dateInterval = handleInterval("day");
        log.info("getCateWordsTop查询周期：开始:{},结束:{}", dateInterval[0], dateInterval[1]);
        conditionMap.put("startDt", dateInterval[0]);
        conditionMap.put("endDt", dateInterval[1]);
        conditionMap.put("zpsrc", paramMap.get("business").equals("wuba") ? "58" : "ganji");
        if ("58".equals(conditionMap.get("zpsrc"))) {
            conditionMap.put("cateNames", "'普工/技工','餐饮','司机/交通服务','家政保洁/安保','物流/仓储','超市/百货/零售','人事/行政/后勤','销售','教育培训','医院/医疗/护理'");
        } else if ("ganji".equals(conditionMap.get("zpsrc"))) {
            conditionMap.put("cateNames", "'司机/交通服务','餐饮','普工/技工','物流/仓储','超市/百货/零售','人事/行政/后勤','家政保洁/安保','客服','影视/娱乐/休闲','计算机/互联网/通信'");
        }
        List<WordTopEntity> cateWordsTop = dorisMapper.getCateWordsTop(conditionMap);
        HashMap<String, List<WordTopEntity>> result = new HashMap<>();
        String firstName = null;
        List<WordTopEntity> tempList = null;
        for (int i = 0; i < cateWordsTop.size(); i++) {
            String catename = cateWordsTop.get(i).getCatename();
            if (i == 0) {
                firstName = catename;
                tempList = new ArrayList<>();
            }
            if (!catename.equals(firstName)) {
                result.put(firstName, tempList);
                firstName = catename;
                tempList = new ArrayList<>();
            }
            tempList.add(cateWordsTop.get(i));
        }
        result.put(firstName, tempList);
        return result;
    }

    @Override
    public Map<String, List<String>> getTopWords() {
        String[] dateInterval = handleInterval("day");
        HashMap<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("startDt", dateInterval[0]);
        conditionMap.put("endDt", dateInterval[1]);
        List<WordTopEntity> cateWordsTop = dorisMapper.getTopWords(conditionMap);
        Map<String, List<String>> map = new HashMap<>();
        ArrayList<String> wubaList = new ArrayList<>();
        ArrayList<String> ganjiList = new ArrayList<>();
        map.put("wuba", wubaList);
        map.put("ganji", ganjiList);

        for (WordTopEntity wordTopEntity : cateWordsTop) {
            if ("58".equals(wordTopEntity.getZpsrc())) {
                wubaList.add(wordTopEntity.getInword());
            } else if ("ganji".equals(wordTopEntity.getZpsrc())) {
                ganjiList.add(wordTopEntity.getInword());
            }
        }
        return map;
    }

    @Override
    public BasicExcelEntity getAreaWordsTopExcel(HashMap<String, String> paramMap) {
        Map<String, List<WordTopEntity>> areaWordsTop = getAreaWordsTop(paramMap);
        String[] split = "北京,广州,深圳,上海,成都,重庆,杭州,武汉,长沙,东莞".split(",");
        List<String> headList = Arrays.asList(split);
        BasicExcelEntity entity = new BasicExcelEntity();

        String business = paramMap.get("business").equals("wuba") ? "58" : "ganji";
        entity.setFilename(business + "_area.xlsx");
        entity.setHeadList(headList);
        entity.setFieldList(headList);

        ArrayList<Map<String, Object>> dataMaps = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            HashMap<String, Object> map = new HashMap<>();
            for (String col : headList) {
                List<WordTopEntity> wordTopEntities = areaWordsTop.get(col);
                map.put(col, wordTopEntities.get(i).getInword());
            }
            dataMaps.add(map);
        }
        entity.setDataMaps(dataMaps);
        return entity;
    }

    @Override
    public BasicExcelEntity getCateWordsTopExcel(HashMap<String, String> paramMap) {
        Map<String, List<WordTopEntity>> areaWordsTop = getCateWordsTop(paramMap);
        String business = paramMap.get("business").equals("wuba") ? "58" : "ganji";

        List<String> headList;
        if ("58".equals(business)) {
            String[] split = "普工/技工,餐饮,司机/交通服务,家政保洁/安保,物流/仓储,超市/百货/零售,人事/行政/后勤,销售,教育培训,医院/医疗/护理".split(",");
            headList = Arrays.asList(split);
        } else {
            String[] split = "司机/交通服务,餐饮,普工/技工,物流/仓储,超市/百货/零售,人事/行政/后勤,家政保洁/安保,客服,影视/娱乐/休闲,计算机/互联网/通信".split(",");
            headList = Arrays.asList(split);
        }
        BasicExcelEntity entity = new BasicExcelEntity();
        entity.setFilename(business + "_cate.xlsx");
        entity.setHeadList(headList);
        entity.setFieldList(headList);

        ArrayList<Map<String, Object>> dataMaps = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            HashMap<String, Object> map = new HashMap<>();
            for (String col : headList) {
                List<WordTopEntity> wordTopEntities = areaWordsTop.get(col);
                if (wordTopEntities.size() > i) {
                    map.put(col, wordTopEntities.get(i).getInword());
                } else {
                    map.put(col, "");
                }

            }
            dataMaps.add(map);
        }
        entity.setDataMaps(dataMaps);
        return entity;
    }
}
